package com.wueasy.demo.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.wueasy.base.exception.InvokeException;
import com.wueasy.base.util.StringHelper;
import com.wueasy.base.vo.PageVo;
import com.wueasy.demo.dto.test.TestAddDto;
import com.wueasy.demo.dto.test.TestEditDto;
import com.wueasy.demo.dto.test.TestIdDto;
import com.wueasy.demo.dto.test.TestQueryPageDto;
import com.wueasy.demo.entity.Test;
import com.wueasy.demo.mapper.TestMapper;
import com.wueasy.demo.service.TestService;
import com.wueasy.demo.vo.TestVo;

@Service
public class TestServiceImpl implements TestService {
	
	@Autowired
	private TestMapper testMapper;

	@Override
	public void add(TestAddDto dto) {
		Test test = new Test();
		BeanUtils.copyProperties(dto, test);
		test.setCreatedDate(new Date());
		testMapper.insert(test);
	}

	@Override
	public void edit(TestEditDto dto) {
		Test test = new Test();
		BeanUtils.copyProperties(dto, test);
		test.setCreatedDate(new Date()); 
		testMapper.updateById(test);
	}

	@Override
	public TestVo get(TestIdDto dto) {
		Test test = testMapper.selectById(dto.getId());
		if(null==test) {
			throw new InvokeException(-1, "记录不存在");
		}
		TestVo vo = new TestVo();
		BeanUtils.copyProperties(test, vo);
		return vo;
	}

	@Override
	public void delete(TestIdDto dto) {
		Test test = testMapper.selectById(dto.getId());
		if(null==test) {
			throw new InvokeException(-1, "记录不存在");
		}
		testMapper.deleteById(dto.getId());
	}

	@Override
	public PageVo<TestVo> queryPage(TestQueryPageDto dto) {
		
		//1. 使用sql方式
//		IPage<Test> page = testMapper.selectPageList(PageDTO.of(dto.getPageNum(), dto.getPageSize()),dto.getName());
		
		
		//2. 使用mybatis plus
		LambdaQueryWrapper<Test> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.like(StringHelper.isNotBlank(dto.getName()), Test::getName,dto.getName());
		lambdaQueryWrapper.orderByDesc(Test::getId);
		IPage<Test> page = testMapper.selectPage(PageDTO.of(dto.getPageNum(), dto.getPageSize()), lambdaQueryWrapper);
		
		
		//旧的转新的page
		PageVo<TestVo> newPage = new PageVo<>();
		newPage.setPageNum(page.getCurrent());
		newPage.setPages(page.getPages());
		newPage.setPageSize((int) page.getSize());
		newPage.setTotal(page.getTotal());
		if(null!=page.getRecords() && !page.getRecords().isEmpty()) {
			List<TestVo> newList = new ArrayList<>();
			for (Test test : page.getRecords()) {
				TestVo vo = new TestVo();
				BeanUtils.copyProperties(test, vo);
				newList.add(vo);
			}
			newPage.setList(newList);
		}
		return newPage;
	}

	
	
}
